import axios from 'axios'
import store from '@/store/index'
import router from '@/router'
import Message from '@/base-ui/message/message'
class Request {
  instance
  constructor(config) {
    this.instance = axios.create(config)
    this.instance.interceptors.request.use(
      (config) => {
        const userInfo = store.state.user.userInfo
        userInfo?.token &&
          (config.headers.Authorization = `Bearer ${userInfo.token}`)

        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        return res.data
      },
      (error) => {
        const status = error.response?.status
        const fullPath = encodeURIComponent(router.currentRoute.value.fullPath)
        switch (status) {
          case 401:
            // 1. 无权限 清空本地无效信息（用户、 token）
            store.commit('user/changeUser', {})
            // 2. 跳转到登录页面
            // 3.跳转需要传参 (当前路径)
            router.replace(`/login?redirectUrl=${fullPath}`)
            break
          case 500:
            Message({ type: 'error', text: '服务器神游中....' })
            break
        }

        return Promise.reject(error)
      }
    )
  }

  request(config) {
    return new Promise((resolve, reject) => {
      this.instance
        .request(config)
        .then((res) => {
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  get(config) {
    return this.request({ ...config, method: 'GET' })
  }

  post(config) {
    return this.request({ ...config, method: 'POST' })
  }

  put(config) {
    return this.request({ ...config, method: 'PUT' })
  }

  delete(config) {
    return this.request({ ...config, method: 'DELETE' })
  }
}

export default Request
